package web;

import helperclasses.AlterLog;
import helperclasses.MyDataColector;
import helperclasses.Product;

import java.io.DataOutput;
import java.io.IOException;
import java.sql.Date;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.AlterLogSave;
import model.ModifyProduct;
import model.ProductsName;
import model.ViewProduct;

/**
 * Servlet implementation class AlterProduct
 */
public class AlterProduct extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AlterProduct() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		if (request.getParameter("m").equals("view")) {
			ViewProduct prod = new ViewProduct();
			try {
				prod.getDetails(Integer.parseInt(request.getParameter("id")));
				request.setAttribute("product", prod.getProduct());
				request.setAttribute("mode", "view");
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else if (request.getParameter("m").equals("add")) {
			request.setAttribute("mode", "add");

		}
		// for autocomplete
		ProductsName pn = new ProductsName();
		request.setAttribute("productsNames", pn.getDesfasurat());
		RequestDispatcher view = request.getRequestDispatcher("displayproduct.jsp");
		view.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String buttonName = "";
		String alterResult = "";
		int count = 1;
		Map<String, String[]> paramMap = request.getParameterMap();
		for (Map.Entry<String, String[]> entry : paramMap.entrySet()) {
			/*
			 * Search for the button name as given in the 'value' attribute for
			 * the input tag
			 */
			if ("Edit".equals(entry.getValue()[0])) {
				buttonName = entry.getKey();
				break;
			} else if ("Delete".equals(entry.getValue()[0])) {
				buttonName = entry.getKey();
				break;
			} else if ("Save".equals(entry.getValue()[0])) {
				buttonName = entry.getKey();
				break;
			}
		}

		if (buttonName.equals("edit")) {
			String checkboxvalue = request.getParameter("alterlog");
			if (!checkboxvalue.equals("isChecked")) {
				Product editProd = new Product();
				ModifyProduct prod = new ModifyProduct();
				MyDataColector dc = new MyDataColector();

				editProd.setProductId(Integer.parseInt(request.getParameter("productId")));
				editProd.setProductName(request.getParameter("productName"));
				editProd.setValoare(Double.parseDouble(request.getParameter("valoare")));
				// editProd.setPretIntrare(Double.parseDouble(request.getParameter("pretIntrare")));
				editProd.setPretIesire(Double.parseDouble(request.getParameter("pretIesire")));
				editProd.setCantitate(Integer.parseInt(request.getParameter("cantitate")));
				editProd.setValoareInStoc(Double.parseDouble(request.getParameter("valoareInStoc")));
				editProd.setUnitateMasura(request.getParameter("um"));
				editProd.setTipNir(Integer.parseInt(request.getParameter("tipNir")));
				// check to see if it's a cocktail
				if (editProd.getTipNir() == 3) {
					while (request.getParameter(count + "_1") != null) {
						try {
							Product ingredient = new Product();
							ingredient.setProductId(dc.getProductId(request.getParameter(count + "_1")));							
							ingredient.setProductName(request.getParameter(count + "_1"));
							ingredient.setValoareInStoc(Double.parseDouble(request.getParameter(count + "_2")));
							editProd.getIngredients().put(ingredient.getProductId(), ingredient);
						} catch (NumberFormatException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (SQLException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						count++;
					}
				}
				try {
					if (prod.EditProduct(editProd)) {
						alterResult = "Editarea realizata cu succes";
					} else {
						alterResult = "Editarea a intampinat o problema";
					}
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				request.setAttribute("mode", "view");
				request.setAttribute("editResult", alterResult);
				request.setAttribute("product", editProd);
				RequestDispatcher view = request.getRequestDispatcher("displayproduct.jsp");
				view.forward(request, response);
			} else {
				AlterLog log = new AlterLog();
				double value;
				DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				java.util.Date date = new java.util.Date();
				log.setProdusId(Integer.parseInt(request.getParameter("productId")));
				log.setAlterDate(dateFormat.format(date));
				log.setOvservatii(request.getParameter("observatii"));
				value = (Double) (Double.parseDouble(request.getParameter("cantitate")) - Double.parseDouble(request
						.getParameter("cantitatehidden")));
				log.setValue(value);
				log.setUser((String) request.getSession().getAttribute("userName"));
				AlterLogSave alterLogSave = new AlterLogSave(log);
				try {
					alterLogSave.saveData();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				response.sendRedirect(response.encodeRedirectURL("stock.do"));
				
				
			}
		} else if (buttonName.equals("save")) {
			Product saveProd = new Product();
			ModifyProduct prod = new ModifyProduct();
			MyDataColector dc = new MyDataColector();
			saveProd.setProductName(request.getParameter("productName"));
			saveProd.setValoare(Double.parseDouble(request.getParameter("valoare")));
			saveProd.setPretIesire(Double.parseDouble(request.getParameter("pretIesire")));
			saveProd.setCantitate(Integer.parseInt(request.getParameter("cantitate")));
			if (request.getParameter("valoareInStoc") == null) {
				saveProd.setValoareInStoc(1);
			} else {
				saveProd.setValoareInStoc(Double.parseDouble(request.getParameter("valoareInStoc")));
			}
			saveProd.setUnitateMasura(request.getParameter("um"));
			saveProd.setTipNir(Integer.parseInt(request.getParameter("tipNir")));
			// check to see if it's a cocktail
			if (saveProd.getTipNir() == 3) {
				while (request.getParameter(count + "_1") != null) {
					try {
						Product ingredient = new Product();
						ingredient.setProductId(dc.getProductId(request.getParameter(count + "_1")));							
						ingredient.setProductName(request.getParameter(count + "_1"));
						ingredient.setValoareInStoc(Double.parseDouble(request.getParameter(count + "_2")));
						saveProd.getIngredients().put(ingredient.getProductId(), ingredient);					
					} catch (NumberFormatException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					count++;
				}
			}
			try {
				if (prod.SaveProduct(saveProd)) {
					alterResult = "Salvarea realizata cu succes";
				} else {
					alterResult = "Salvarea a intampinat o problema. Verifica datele sau Nume duplicate";
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			RequestDispatcher view = request.getRequestDispatcher("stock.do");
			view.forward(request, response);
		}

	}

}
